Problem
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = “abcd”
t = “abcde”
Output: e
Explanation: ‘e’ is the letter that was added.
Pre analysis
It is same as finding extra number in two arrays. will substract summation of one with other.
Another Solution
-
Same Approach using
^var findTheDifference = function(s, t) { let result = 0; for(let i=0;i<t.length;i++) { result = result ^ t.charCodeAt(i); if(i<=s.length-1) { result = result ^ s.charCodeAt(i); } } return String.fromCharCode(result); }; -
Sorting and finding O(N2)
var findTheDifference = function(s, t) { s = s.split('').sort(); t = t.split('').sort(); for(let i = 0; i < t.length; i++) { if(s[i] !== t[i]) { return t[i] } } };